<?php

require_once("../config/start.php");
require_module("namelink");

$parameters =& $_GET;
if(!$parameters) $parameters =& $_POST;

$document_url = @urldecode($parameters["document_url"]);
$document_text = htmlspecialchars_decode(urldecode(@$parameters["document_text"]));
$document_id = @$parameters["document_id"];
$identifier_source = @urldecode($parameters["identifier_source"]);
$response_format = @$parameters["response_format"];
$document_format = @$parameters["document_format"];

if($document_format != 'json') $document_format = 'xml';


if($document_url)
{
    //echo $document_url;
    $html = get_remote_page($document_url);
    //echo "$html";
}elseif($document_text)
{
    $html = $document_text;
}else
{
    echo 'enter document_url or document_text';
    exit;
}

$all_names = NameTag::find_names($html);

$i = 0;
$indices = array();
$merged_all_names = array();
foreach($all_names as $name)
{
    if(@$index = $indices[$name['dwc:ScientificName']])
    {
        $merged_all_names[$index]['offsets'][] = $name['offsets'][0];
    }else
    {
        $merged_all_names[] = $name;
        $indices[$name['dwc:ScientificName']] = $i;
        $i++;
    }
}
//print_r($all_names);

$response = array();
if($document_id) $response['documentId'] = $document_id;
else $response['documentId'] = md5(uniqid("taxonfinder".rand(), true));
$response['names'] = $merged_all_names;





if($response_format == 'json')
{
    echo json_encode($response);
}else
{
    header('Content-type: text/xml');
    echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n";
    echo "<result xmlns:dwc=\"http://rs.tdwg.org/dwc/dwcore/\">\n";
    
    array_as_xml($response, '  ');
    
    echo "</result>";
}

function array_as_xml($array, $prefix = '', $element = '')
{
    foreach($array as $key => $value)
    {
        if(is_int($key)) $key = $element ? $element : "value";
        
        if(is_array($value))
        {
            // if(preg_match("/^(.*)\*$/", $key, $arr))
            // {
            //     array_as_xml($value, $prefix, $arr[1]);
            //     continue;
            // }
            
            echo $prefix."<". $key .">\n";
            array_as_xml($value, $prefix."  ", substr($key, 0, -1));
            echo $prefix."</". $key .">\n";
        }else
        {
            echo $prefix."<".$key.">".htmlspecialchars($value)."</".$key.">\n";
        }
    }
}



?>